package com.sanq.product.books.utils;

import com.sanq.product.books.entity.vo.JobsVo;
import com.sanq.product.config.utils.web.LogUtil;
import org.quartz.*;

import java.util.List;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

public class JobManage {

    /**
     * 通过名称得到类名
     *
     * @param clazz
     * @return
     * @throws ClassNotFoundException
     */
    public static Class<? extends Job> getClass(String clazz) throws ClassNotFoundException {
        return (Class<? extends Job>) Class.forName(clazz);
    }

    /**
     * 开始任务
     *
     * @param jobsVo
     */
    public static void startJob(Scheduler scheduler, JobsVo jobsVo) throws Exception {

        JobKey jobKey = new JobKey(String.format("job:name:%s", jobsVo.getId()), String.format("job:group:%s", jobsVo.getId()));

        stopJob(scheduler, jobsVo.getId());

        JobDetail jobDetail;
        if (scheduler.checkExists(jobKey))
            jobDetail = scheduler.getJobDetail(jobKey);
        else
            jobDetail = newJob(getClass(jobsVo.getJobClazz()))
                    .withIdentity(jobKey)
                    .usingJobData("extra", jobsVo.getExtra())
                    .build();

        CronTrigger trigger = newTrigger()
                    .withIdentity(String.format("cron:trigger:%s", jobsVo.getId()), String.format("cron:group:%s", jobsVo.getId()))
                    .withSchedule(cronSchedule(jobsVo.getCron()))
                    .build();

        scheduler.scheduleJob(jobDetail, trigger);

        if (!scheduler.isShutdown()) {
            scheduler.start();
        }
    }

    public static void startJob(Scheduler scheduler, List<JobsVo> jobsVoList) {
        jobsVoList.stream().forEach(jobsVo -> {
            try {
                startJob(scheduler, jobsVo);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 停止任务
     * @param scheduler
     * @param id
     * @throws SchedulerException
     */
    public static void stopJob(Scheduler scheduler, Long id) throws SchedulerException {
        scheduler.deleteJob(new JobKey(String.format("job:name:%s", id), String.format("job:group:%s", id)));
    }

}

